var fs = require('fs');
var path = require('path');
const imagemin = require('imagemin');
const imageminPngquant = require('imagemin-pngquant');

function readFileList(dir, filesList = []) {
    const files = fs.readdirSync(dir);
    files.forEach((item, index) => {
        var fullPath = path.join(dir, item);
        const stat = fs.statSync(fullPath);
        if (stat.isDirectory()) {
            readFileList(path.join(dir, item), filesList); //递归读取文件
        } else {
            var extname = path.extname(fullPath)
            if (extname == ".png" || extname == ".jpg") {
                filesList.push(fullPath);
            }
        }
    });
    return filesList;
}

async function handleImage(min, max) {
    var imageList = [];
    readFileList('./public/images', imageList);
    console.log(min, max);
    var str = "源文件（单位：kb）" + ",压缩后（单位：kb）\n";
    for (let index = 0; index < imageList.length; index++) {
        const element = imageList[index];
        var _newPath = path.dirname(element);
        var _fileName = path.basename(element);
        _newPath = _newPath.replace('public/images', "");
        var _newFolder = "public/build/" + min + "_" + max;
        _newPath = _newFolder + _newPath;
        const _res = await imagemin([element], {
            destination: _newPath,
            plugins: [
                imageminPngquant({
                    quality: [parseFloat(min), parseFloat(max)]
                })
            ]
        });
        console.log(_res);
        console.log(_newPath + "/" + _fileName);
        const _originStat = fs.statSync(element);
        const _newStat = fs.statSync(_newPath + "/" + _fileName);
        str += (_originStat.size / 1024).toFixed(2) + "," + (_newStat.size / 1024).toFixed(2) + "\n";
    }
    fs.writeFileSync(_newFolder + "/" + min + "_" + max + '.csv', str, (err) => {
        console.log('写入文件', err);
    });
    return true;
}

module.exports.handleImage = handleImage;